#!/bin/bash

echo "############################################################"
echo "      get playlist file for mplayer"
echo " 	    scripts by hitmoon, <zxq_yx_007@163.com>"
echo "############################################################"


usage()
{
	echo "Usage: get-music-play-list.sh <directory of songs> [-o out-put-list] [-c auto rename]"
	exit 1
}


if [ $# -lt 1 ];then
	usage
fi

# songs directory
SONGS_DIR="./"
DEST=p3-list
RN="no"

while [ $# -ge 1 ]
do
	case $1 in
	-c)
	     RN="yes"
	     shift;;
	-o)
	     DEST=$2
	     shift 2;;
	-*)
	     echo "unknow option $1!"
	     usage;;
	*)
	     SONGS_DIR="$1"
	     shift;;
	
	esac
done


LEN=${#SONGS_DIR}

if [ ${SONGS_DIR:$LEN-1:1} == "/" ];then
	SONGS_DIR=${SONGS_DIR:0:$LEN-1}
fi
	
if [ "X${1:0:1}" != "X/" ];then
	SONGS_DIR="${PWD}/${SONGS_DIR}"
fi


if [ -n "$2" ];then
	DEST=$2
fi

echo "output list name is '${DEST}'"
# rename songs and generate the new list
echo -n "" > ${DEST}

num=1

find  $SONGS_DIR -type f -regextype egrep -regex ".*\.(flac|ape|wav|mp3|ogg)" 2>/dev/null | while read file
  do 
  	f=${file##*/}
	DIR=$(dirname "$file")
	if [ "X$RN" == "Xyes" ]; then
		
		newf=$(echo "$f" | sed -r -e 's/ +\././g' -e 's/\. +/./g' \
		-e 's/^([0-9]+[-.]+)+//g' -e 's/-/ /g' -e 's/ +/-/g') 
		newf="$num-$newf"
		num=$(($num + 1))
		mv -v "$DIR/$f" "$DIR/$newf" 2>/dev/null
		echo "$DIR/$newf" >> ${DEST}
	else
		
		echo "$DIR/$f" >> ${DEST}
	fi
done

echo "########################################################"
echo "Generate new mp3 list Done!"
num=$(cat ${DEST} | awk 'BEGIN{total=0}{total++}END{print total}')
echo "You have $num songs in the list '${DEST}', Enjoy!" 
echo "########################################################"

